
package com.compuvest.web;
/*
 * # update every hour advertshow
 * 29,59 * * * * root /usr/bin/wget --quiet -O /dev/null http://www.compuvest.com/advertshow?update=update
 *
*/

// <editor-fold defaultstate="collapsed" desc="import">
import java.io.IOException;
import java.io.PrintWriter;

import java.util.Map;
import java.util.HashMap;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// </editor-fold>

public class AdvertShow extends HttpServlet {

// <editor-fold defaultstate="collapsed" desc="init variables">
    private static final Logger logger = Logger.getLogger(AdvertShow.class.getName());

    public static final int COMPUVEST   = 1;
    public static final int BIZRATE     = 3;
    public static final int AMEX        = 4;
    public static final int ADV_CWS     = 6; // advert for our customer
    public static final int GRABBER     = 7;
    public static final int NEXTTAG     = 8;
    public static final int ADV_CWM     = 13; // advert for spam customer
    public static final int ONETIME     = 14;
    public static final int CJ          = 15;
    public static final int SHOPING     = 16;
    public static final int FROOGLE     = 18;
    public static final int LINKSHARE   = 22;
    public static final int BING        = 26;
    public static final int FACEBOOK    = 120;
    public static final int CATCH       = 121;

    private static Map<String,Advert> advertID;

    private static Map itemsCategoryPage;
    private static Map itemsSubcategoryPage;
    private static Map itemsFirstPage;

    private static String itemsSearchPage;

    private static String leftMenu;
    private static String country;
    private static String allstate;
    private static String usastate;
    private static Map usastatemap;
    private static String brandPage;
    //

    private SQLBean mysql;
    private static Random rgen;
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="init(ServletConfig config)">

    @Override
    public void init(ServletConfig config) throws ServletException {
	super.init(config);

        mysql = (SQLBean)config.getServletContext().getAttribute("sb");
	if(mysql == null) {
            logger.log(Level.SEVERE, "init() sb=null ");
        }

        rgen = new Random();

        Map<String,Long> times = initValues();

	logger.log(Level.SEVERE, "Init: " + times.toString());
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="processRequest()">

    protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	if(request.getParameter("update") != null) {

            response.setContentType("text/xml;charset=UTF-8");

            Map<String,Long> times = initValues();

            StringBuilder xml = new StringBuilder();
            xml.append("<?xml version='1.0' encoding='UTF-8'?>");
            xml.append("<status>");
            xml.append("<adverttable>").append(times.get("adverttable")).append("ms.</adverttable>");
            xml.append("<brandpage>").append(times.get("brandpage")).append("ms.</brandpage>");
            xml.append("<leftmenu>").append(times.get("leftmenu")).append("ms.</leftmenu>");
            xml.append("<country>").append(times.get("country")).append("ms.</country>");
            xml.append("<allstate>").append(times.get("allstate")).append("ms.</allstate>");
            xml.append("<usastate>").append(times.get("usastate")).append("ms.</usastate>");
            xml.append("<itemscategory>").append(times.get("itemscategory")).append("ms.</itemscategory>");
            xml.append("<itemssubcat>").append(times.get("itemssubcat")).append("ms.</itemssubcat>");
            xml.append("<itemsfirstpage>").append(times.get("itemsfirstpage")).append("ms.</itemsfirstpage>");
            xml.append("<itemssearchpage>").append(times.get("itemssearchpage")).append("ms.</itemssearchpage>");
            xml.append("</status>");

            PrintWriter out = response.getWriter();
            try {
		out.print(xml.toString());
            }
            finally {
		out.close();
            }
	}
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="initValues">

    private Map<String,Long> initValues() {

        long startEvent = 0L;
        Map<String,Long> times = new HashMap<String,Long>();
	// advert map
        startEvent = System.currentTimeMillis();
	advertID = mysql.getAdvertTable();
        times.put("adverttable", System.currentTimeMillis() - startEvent);

        startEvent = System.currentTimeMillis();
        country = mysql.getCountry();
        times.put("country", System.currentTimeMillis() - startEvent);

        startEvent = System.currentTimeMillis();
        allstate = mysql.getAllState();
        times.put("allstate", System.currentTimeMillis() - startEvent);

        startEvent = System.currentTimeMillis();
        usastate = mysql.getUsaState();
        times.put("usastate", System.currentTimeMillis() - startEvent);

        startEvent = System.currentTimeMillis();
        usastatemap = mysql.getUsaStateMap();
        times.put("usastatemap", System.currentTimeMillis() - startEvent);

        startEvent = System.currentTimeMillis();
        leftMenu = mysql.getLeftMenuJSON();
        times.put("leftmenu", System.currentTimeMillis() - startEvent);

        startEvent = System.currentTimeMillis();
        brandPage = mysql.getBrandPage();
        times.put("brandpage", System.currentTimeMillis() - startEvent);

        startEvent = System.currentTimeMillis();
        itemsCategoryPage = mysql.getItemsCategoryPage();
        times.put("itemscategory", System.currentTimeMillis() - startEvent);

        startEvent = System.currentTimeMillis();
        itemsSubcategoryPage = mysql.getItemsSubcategoryPage();
        times.put("itemssubcat", System.currentTimeMillis() - startEvent);

        startEvent = System.currentTimeMillis();
	itemsFirstPage = mysql.getFirstPage();
        times.put("itemsfirstpage", System.currentTimeMillis() - startEvent);

        startEvent = System.currentTimeMillis();
	itemsSearchPage = mysql.getItemsSearchPage();
        times.put("itemssearchpage", System.currentTimeMillis() - startEvent);

        return times;
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getString Int Double">

    public String getString(String value, String defVal) {
        return value != null ? value : defVal;
    }

    public int getInt(String value, int defInt) {

        int integer = defInt;
        try {
            integer = Integer.parseInt(value);
        }
        catch(Exception ignore) { }

        return integer;
    }

    public long getLong(String value, long defInt) {

        long longValue = defInt;
        try {
            longValue = Long.parseLong(value);
        }
        catch(Exception ignore) { }

        return longValue;
    }

    public double getDouble(String value, double defDouble) {

        double dbl = defDouble;
        try {
            dbl = Double.parseDouble(value.replace('$','0'));
        }
        catch(Exception ignore) { }

        return dbl;
    }

//    public synchronized int getFloatToInt(String value, int defInt) {
    public int getFloatToInt(String value, int defInt) {

        int result = defInt;
        float flt;
        try {
            flt = Float.parseFloat(value);
            result = (int)flt;
            if(flt < 0f) {
                result = 0;
            }
            else if(flt > 65536f) {
                result = 65536;
            }
        }
        catch(Exception ignore) { }

        return result;
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="GET">

    final int[] catIDs = { 573, 446, 9, 30, 304, 13, 397, 625 };

//    public synchronized int getAdvertRandomCategory() {
    public int getAdvertRandomCategory() {

        return catIDs[rgen.nextInt(catIDs.length)];
    }

//    public synchronized String getItemsCategoryPage(String categoryID) {
    public String getItemsCategoryPage(String categoryID) {

        return (String)itemsCategoryPage.get(categoryID) == null ? "[]" : (String)itemsCategoryPage.get(categoryID);
    }

//    public synchronized String getItemsSubcategoryPage(String subcategoryID) {
    public String getItemsSubcategoryPage(String subcategoryID) {

        return (String)itemsSubcategoryPage.get(subcategoryID) == null ? "[]" : (String)itemsSubcategoryPage.get(subcategoryID);
    }

//    public synchronized String getItemsFirstPage(String categoryID) {
    public String getItemsFirstPage(String categoryID) {

        return (String)itemsFirstPage.get(categoryID) == null ? "[]" : (String)itemsFirstPage.get(categoryID);
    }

//    public synchronized String getItemsSearchPage() {
    public String getItemsSearchPage() {

        return itemsSearchPage;
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="isFreeShipping()">

    public boolean isFreeShipping(String advert) {

        return (advert.contains("oogle") || getAdvertID(advert) == AdvertShow.ADV_CWS || getAdvertID(advert) == AdvertShow.ADV_CWM || getAdvertID(advert) == AdvertShow.BING);
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getAdvertID()">

    public int getAdvertID(String name) {

        return advertID.containsKey(name) ? advertID.get(name).getAdvertID() : advertID.get("compuvest").getAdvertID();
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getAdvertPrefix()">

    public String getAdvertPrefix(String name) {

        return advertID.containsKey(name) ? advertID.get(name).getPrefix() : advertID.get("compuvest").getPrefix();
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getLeftMenu()">

//    public synchronized String getLeftMenu() {
    public String getLeftMenu() {

        return leftMenu;
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getCountryList() selectCountryString()">

//    public synchronized String getCountryList(String countryCode) {
    public String getCountryList(String countryCode) {
	return new String(AdvertShow.country).replace("='" + countryCode + "'", "='" + countryCode + "' selected=\"yes\"");
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getAllStateList()">

    public String getAllStateList(String stateCode) {

        return new String(AdvertShow.allstate).replace("='" + stateCode + "'", "='" + stateCode + "' selected=\"yes\"");
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getUsaStateList()">

    public String getUsaStateList(String stateCode) {

        return new String(AdvertShow.usastate).replace("='" + stateCode + "'", "='" + stateCode + "' selected=\"yes\"");
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getAdvertID()">

    public String getUsaState(String statename) {

        return usastatemap.containsKey(statename.toLowerCase()) ? (String)usastatemap.get(statename.toLowerCase()) : null;
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="getBrandPage() selectBrandPageString()">

    public String getBrandPage() {
	return AdvertShow.brandPage;
    }
// </editor-fold>

// <editor-fold defaultstate="collapsed" desc="HttpServlet methods.">

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    } 

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "AdvertShow";
    }

    @Override
    public void destroy() {
        super.destroy();

	logger.log(Level.SEVERE, "Destroy:");
    }
// </editor-fold>

}
